package com.yangye.pidoublename.service.impl;

import com.yangye.pidoublename.service.DoubleNameService;
import com.yangye.pidoublename.service.ProvinceEnum;
import com.yangye.pidoublename.vo.DoubleNameVo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author yangye
 * @date 2019/9/12
 */
@Service
public class JiangSuServiceImpl implements DoubleNameService {

	private final String QUERY_URL = "http://www.wjw.jsga.gov.cn/cname/index";

	@Autowired
	private RestTemplate restTemplate;

	@Override
	public DoubleNameVo findByName(String name) {
		MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
		params.add("name", name);
		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
		HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(params, httpHeaders);
		ResponseEntity<String> response = restTemplate.postForEntity(QUERY_URL, request, String.class);
		String body = response.getBody();

		// 解析html
		Document doc = Jsoup.parse(body);
		int man = Integer.parseInt(doc.select(".tongming-man span").first().text());
		int woman = Integer.parseInt(doc.select(".tongming-woman span").first().text());

		DoubleNameVo doubleNameVo = new DoubleNameVo();
		doubleNameVo.setMan(man);
		doubleNameVo.setWoman(woman);
		doubleNameVo.setTotal(man + woman);
		doubleNameVo.setName(name);
		doubleNameVo.setProvince(ProvinceEnum.JIANGSU.getName());
		return doubleNameVo;
	}
}
